package com.example.deploysinggle.test1.common.filter;


import com.example.deploysinggle.test1.common.context.QiuContext;
import io.micrometer.core.instrument.util.StringUtils;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;


/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/12/15 19:17
 */
public class CommonFilter implements Filter {
    private static final String TRACE_ID = "traceId";
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if(request instanceof HttpServletRequest){
            HttpServletRequest httpRequest = (HttpServletRequest) request;
             String traceId = httpRequest.getHeader(TRACE_ID);
             if(StringUtils.isBlank(traceId)){
                 traceId = UUID.randomUUID().toString();
             }
            MDC.put(TRACE_ID, traceId);
            QiuContext.setReqPath(httpRequest.getServletPath().trim());

            try {
                chain.doFilter(request, response);
            } finally {
                MDC.remove(TRACE_ID);
                QiuContext.removeReqPath();
            }

        }
    }

    // 放 path 和 traceId

}
